package com.qf.spring2202.proxypattern.utils;

import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 在spring的 FactoryBean 中进行动态代理对象的创建
 */
public class MyProxyFactoryBean implements FactoryBean<Object> {

    private Object target;

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    @Override
    public Object getObject() throws Exception {

        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // 判断一下，，method是不是属于 Object 类型 ，如果是Object中定义的方法，则不做时间统计
                        if (method.getDeclaringClass().equals(Object.class)) {
                            //2. 让原始对象的目标方法执行
                            final Object result = method.invoke(target, args);
                            return result;
                        }

                        //1. 添加辅助功能
                        final long start = System.currentTimeMillis();

                        //2. 让原始对象的目标方法执行
                        final Object result = method.invoke(target, args);

                        final long end = System.currentTimeMillis();
                        System.out.println("time usesd = "+(end-start));

                        return result;
                    }
                });

    }

    @Override
    public Class<?> getObjectType() {
        return Object.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
